<template>
  <e-container :loading="loading">
    <e-title title="Basic Information" />
    <a-divider />
    <div class="form">
      <a-form ref="formInstance" :model="apiData" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Client Name" name="fullName">
              <a-tooltip
                :visible="nameIsExist.exits"
                placement="left"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <template #title> Already have a client named {{ nameIsExist.name }} </template>
                <a-input
                  :disabled="briefInfo.isExisting"
                  v-model:value="apiData.fullName"
                  @blur="checkClientNameExist"
                />
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Country/Region" name="countryID">
              <e-country-region-select
                v-model="countryIDWrapped"
                :disabled="briefInfo.isExisting"
                :allow-clear="false"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Abbreviation" name="shortName">
              <a-input v-model:value="apiData.shortName" :disabled="briefInfo.isExisting" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="City/State" name="city">
              <a-input v-model:value="apiData.city" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Organization" name="parentID">
              <a-select
                v-model:value="parentIDWrapped"
                style="width: calc(100% - 100px)"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                show-search
                class="addable"
                placeholder="Please select or input to create"
                option-filter-prop="label"
              >
                <!-- 数据库中已有的 -->
                <a-select-option v-for="item in dict.organizations" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
                <!-- 用户手动添加的 -->
                <a-select-option v-for="item in tempOrganizations" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
              <a-button type="primary" ghost style="width: 96px; margin-left: 4px" @click="showAddOrganization = true">
                <a-space>
                  <e-icon type="add" font-size="16px" />
                  Create
                </a-space>
              </a-button>
            </a-form-item>
            <a-modal
              v-model:visible="showAddOrganization"
              width="888px"
              title="Create New Organization"
              wrap-class-name="primary-modal"
              ok-text="Save"
              :destroyOnClose="true"
              @cancel="showAddOrganization = false"
            >
              <a-form ref="addOrganizationFormRef" layout="vertical" :model="organizationFormForAdd">
                <a-form-item label="Organization Name" :rules="addOrganizationRules" name="name">
                  <a-input v-model:value="organizationFormForAdd.name" placeholder="Please Input Organization Name" />
                </a-form-item>
              </a-form>
              <template #footer>
                <a-button key="back" @click="showAddOrganization = false">Cancel</a-button>
                <a-button key="submit" type="primary" :loading="buttonLoading" @click="handleAddOrganization">
                  Create
                </a-button>
              </template>
            </a-modal>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Time Zone" name="timeZone">
              <a-select
                v-model:value="timeZoneWrapped"
                show-search
                option-filter-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.timeZones" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Client Nature" name="clientKind">
              <e-radio v-model="apiData.clientKind" :options="dict.clientTypes" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Zip Code" name="postalCode">
              <a-input v-model:value="apiData.postalCode" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Business Area" name="businessDirection">
              <e-radio v-model="apiData.businessDirection" disabled :options="dict.businessAreas" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="clientTier">
              <template #label>
                <client-tier-tip />
              </template>
              <a-select v-model:value="clientTierWrapped" :get-popup-container="triggerNode => triggerNode.parentNode">
                <a-select-option v-for="item in dict.clientTiers" :key="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Client Industry" name="saleBUID">
              <a-select
                v-model:value="saleBUIDWrapped"
                show-search
                option-filter-prop="label"
                :disabled="briefInfo.isExisting"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.salesBUs" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="My BU" name="hrSalesBUID">
              <a-select
                v-model:value="hrSalesBUIDWrapped"
                :disabled="briefInfo.isExisting"
                show-search
                option-filter-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.ownersBUs" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="E-mail" name="email">
              <a-input v-model:value="apiData.email" @blur="() => (apiData.email = apiData.email.trim())" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Operate BU" name="operateBU">
              <a-select
                v-model:value="OperateBUWrapped"
                show-search
                allow-clear
                option-filter-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.operateBUs" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item name="url">
              <template #label>
                <url-tip />
              </template>
              <a-input v-model:value="apiData.url" @blur="() => (apiData.url = apiData.url.trim())" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Office Phone" name="telephone">
              <a-input v-model:value="apiData.telephone" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Address" name="address">
              <a-input v-model:value="apiData.address" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Remark" name="description">
              <a-textarea v-model:value="apiData.description" :auto-size="{ minRows: 4, maxRows: 4 }" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleClientCancel">Cancel</a-button>
        <a-button v-permission="'BasicInformation:Edit'" type="primary" @click="handleClientSave">Save</a-button>
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { computed, reactive, ref, inject, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import EIcon from '@/components/EIcon.vue'
import ERadio from '@/components/ERadio.vue'
import TargetClient from '@/api/targetClient.js'
import BasicInfo from '@/api/client/basicInfo.js'
import ECountryRegionSelect from '@/components/ECountryRegionSelect.vue'
import { useBasicInfo } from '@/pages/Client/hooks/useBasicInfo.js'
import { useDictNullValue } from '@/hooks/useDictNullValue.js'
import { CHECK_FORM_INTEGRITY, CONFIRM_BACK_TO_DETAIL, UPDATE_CLIENT_SUCCESS } from '@/constants/message.js'
import { useRules } from '@/pages/Client/basicInformation/useRules.js'
import ClientTierTip from '@/pages/components/ClientTierTip.vue'
import UrlTip from '@/pages/components/URLTip.vue'
import { useDict } from '@/hooks/useDict.js'
import { useAddNewOrganization } from '@/pages/Client/hooks/useAddNewOrganization.js'
const { Modal, message } = inject('Feedback')
const gutter = [120, 16]
const loading = ref(true)
const route = useRoute()
const clientId = route.params.id
const router = useRouter()
const store = useStore()
const dict = useDict()
const briefInfo = computed(() => store.state.client.briefInfo)
const formInstance = ref(null)
const apiData = reactive({
  // 客户名称（Client Name）
  fullName: '',
  // 国家与地区（Country/Region）
  countryID: 0,
  // 客户简称（Abbreviation）
  shortName: '',
  // 城市（City/State）
  city: '',
  // 客户组织（Organization）
  parentID: 0,
  // 新建的客户名
  OrganizationName: null,
  // 时区（Time zone）
  timeZone: '',
  // 客户性质（Client Nature）
  clientKind: '',
  // 邮编（Zip Code）
  postalCode: '',
  // 客户所属销售 BU（Sales BU）
  saleBUID: '',
  // my BU
  hrSalesBUID: '',
  // 运营BU
  operateBU: '',
  // 客户等级（Client Tier）
  clientTier: '',
  // 商业区域（Business Area）
  businessDirection: '',
  // 电子邮箱（E-mail）
  email: '',
  // 办公电话（Office Phone）
  telephone: '',
  // 网站（URL）
  url: '',
  // 地址（Address）
  address: '',
  // 备注（Remark）
  description: ''
})
// 新建组织
const addOrganizationFormRef = ref(null)
const {
  organizationFormForAdd,
  tempOrganizations,
  showAddOrganization,
  addOrganizationRules,
  buttonLoading,
  handleAddOrganization
} = useAddNewOrganization(addOrganizationFormRef, dict, apiData)
const countryIDWrapped = useDictNullValue(apiData, 'countryID')
const saleBUIDWrapped = useDictNullValue(apiData, 'saleBUID')
const clientTierWrapped = useDictNullValue(apiData, 'clientTier')
const hrSalesBUIDWrapped = useDictNullValue(apiData, 'hrSalesBUID', dict, 'ownersBUs')
const OperateBUWrapped = useDictNullValue(apiData, 'operateBU')
const parentIDWrapped = useDictNullValue(apiData, 'parentID')
const timeZoneWrapped = useDictNullValue(apiData, 'timeZone')
const rules = useRules(clientId, apiData, dict)
// 根据选择的国家自动选择时区
watch(
  () => countryIDWrapped.value,
  countryId => {
    TargetClient.getTimeZoneByCountryID(countryId).then(({ data }) => {
      apiData.timeZone = data && data !== '0' ? data : ''
    })
  }
)
const nameIsExist = ref({
  exits: false,
  name: ''
})
// 提示名称已存在
const checkClientNameExist = () => {
  if (apiData.fullName) {
    TargetClient.isUniqueClientName(apiData.fullName, clientId).then(res => {
      if (res.data) {
        nameIsExist.value.exits = true
        nameIsExist.value.name = apiData.fullName
      } else {
        nameIsExist.value.exits = false
      }
    })
  }
}
new Promise(resolve => {
  useBasicInfo(clientId, resolve)
}).then(basicInfo => {
  loading.value = false
  Object.keys(apiData).forEach(key => {
    apiData[key] = basicInfo.raw.value[key]
  })
})
const handleClientCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push({ name: 'Basic Information' })
    }
  })
}
const emits = defineEmits(['updated'])
const handleClientSave = () => {
  formInstance.value
    .validate()
    .then(() => {
      loading.value = true
      BasicInfo.update(clientId, apiData)
        .then(() => {
          message.success(UPDATE_CLIENT_SUCCESS)
          emits('updated')
          router.replace({ name: 'Basic Information' })
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {
      message.error(CHECK_FORM_INTEGRITY)
    })
}
</script>
<style lang="less" scoped>
.form {
  padding: 0 228px;
  .addable {
    .ant-select-item-empty {
      display: none;
    }
  }
}
.buttons {
  text-align: center;
}
</style>
<route lang="yaml">
name: Edit Basic Information
path: '/client/:id/basic-information/edit'
meta:
  title: Edit Basic Information
  permission: BasicInformation
</route>
